package com.yuncheng.spcyApi.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.dto.SysJobDto;
import com.yuncheng.spcyApi.entity.SpcyRsMhpzRole;
import com.yuncheng.spcyApi.entity.SysRole;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.ISpcyRsMhpzRoleService;
import com.yuncheng.spcyApi.service.ISysRoleService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsMhpz;
import com.yuncheng.spcyApi.service.ISpcyRsMhpzService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.TreeVo;
import io.swagger.annotations.ApiImplicitParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description: 审评查验-门户配置
 * @Author: yuncheng
 * @Date: 2023-05-29
 * @Version: V1.0
 */
@Api(tags = "审评查验-门户配置接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsMhpz")
public class SpcyRsMhpzController extends BaseController<SpcyRsMhpz, ISpcyRsMhpzService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsMhpzController.class);

    @Resource
    private ISpcyRsMhpzService spcyRsMhpzService;

    @Resource
    private ISpcyRsMhpzRoleService spcyRsMhpzRoleService;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    /**
     * 分页列表查询
     *
     * @param spcyRsMhpz
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "门户配置-分页列表查询")
    @ApiOperation(value = "门户配置-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SpcyRsMhpz spcyRsMhpz,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsMhpz> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyRsMhpz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(spcyRsMhpz.getFmc()),SpcyRsMhpz::getFmc,spcyRsMhpz.getFmc());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsMhpz.getFlj()),SpcyRsMhpz::getFlj,spcyRsMhpz.getFlj());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsMhpz.getFsfyx()),SpcyRsMhpz::getFsfyx,spcyRsMhpz.getFsfyx());
        queryWrapper.like(StringUtils.isNotBlank(spcyRsMhpz.getFgwsq()),SpcyRsMhpz::getFgwsq,spcyRsMhpz.getFgwsq());
        queryWrapper.orderByAsc(SpcyRsMhpz::getFqxdj);
        IPage<SpcyRsMhpz> pageList = spcyRsMhpzService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }


    /**
     * 添加
     *
     * @param spcyRsMhpz
     * @return
     */
    @Log(title = "审评查验-门户配置-添加")
    @ApiOperation(value = "审评查验-门户配置-添加")
    @PostMapping(value = "/addMhpz")
    public HttpResult<?> addMhpz(@RequestBody SpcyRsMhpz spcyRsMhpz) {
        spcyRsMhpz.setId(GetUuIdUtils.ReplaceUuId());
        spcyRsMhpzService.save(spcyRsMhpz);

        return HttpResult.ok("添加成功");
    }

    @Log(title = "获取所有角色和已经授权角色")
    @ApiOperation(value = "获取所有角色和已经授权角色")
    @ApiImplicitParam(name = "id",value = "门户id")
    @GetMapping(value = "queryAllRoleAndAuth")
    public HttpResult<?> queryAllRoleAndAuth(String id){
        if (StringUtils.isBlank(id)){
            return HttpResult.error("主要参数不能为空");
        }
        Map resultMap = new HashMap();
        List<SysRole> roleList = sysRoleService.list(new LambdaQueryWrapper<SysRole>().orderByAsc(SysRole::getRoleOrder));
        List<TreeVo> treeRoleList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleList)) {
            treeRoleList = roleList.stream().map(f -> new TreeVo(f.getId(), f.getRoleName())).collect(Collectors.toList());
        }

        List<SpcyRsMhpzRole> bhpzRoleList = spcyRsMhpzRoleService.list(new LambdaQueryWrapper<SpcyRsMhpzRole>()
                .eq(SpcyRsMhpzRole::getFmhid, id));
        List<String> roleIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(bhpzRoleList)){
            roleIds = bhpzRoleList.stream().map(SpcyRsMhpzRole::getFroleid).filter(f->StringUtils.isNotBlank(f)).collect(Collectors.toList());
        }
        resultMap.put("allRoles",treeRoleList);
        resultMap.put("roleIds",roleIds);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "获取所有岗位数据列表")
    @ApiOperation(value = "获取所有岗位数据列表")
    @GetMapping(value = "getAllGwList")
    public HttpResult getAllGwList(){

        List<SysJobDto> gwList = ycSysUserMapper.getAllGw();
        return HttpResult.ok(gwList);
    }

    @Log(title = "获取当前登录用户授权的门户权限")
    @ApiOperation(value = "获取当前登录用户授权的门户权限")
    @GetMapping(value = "getNowMhpzUrl")
    public HttpResult getNowMhpzUrl(){
        Map resultMap = new HashMap();
        String url = "";

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("当前登录已失效！请重新登录！");
        }
        List<SysJobDto> userJobList = ycSysUserMapper.getUserGwByUserId(new SysJobDto(), currentUser.getId());

        LambdaUpdateWrapper<SpcyRsMhpz> wrapper = new LambdaUpdateWrapper<>();

        // 用户所处岗位
        if (CollectionUtil.isNotEmpty(userJobList)) {
            List<String> gwList = userJobList.stream().map(SysJobDto::getId).collect(Collectors.toList());
            wrapper.in(SpcyRsMhpz::getFgwsq, gwList);
        }

        wrapper.orderByAsc(SpcyRsMhpz::getFqxdj);
        List<SpcyRsMhpz> mhList = spcyRsMhpzService.list(wrapper);
        if (CollectionUtil.isNotEmpty(mhList)){
            url = mhList.get(0).getFlj();
        }

        resultMap.put("url", url);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "门户配置-角色授权-添加")
    @ApiOperation(value = "门户配置-角色授权-添加")
    @PostMapping(value = "addMhpzRole")
    public HttpResult<?> addMhpzRole(@RequestBody SpcyRsMhpzRole rsMhpzRole){
        if (StringUtils.isBlank(rsMhpzRole.getFmhid())){
            return HttpResult.error("门户参数不能为空");
        }
        if (StringUtils.isBlank(rsMhpzRole.getFroleid())){
            return HttpResult.error("角色参数不能为空");
        }
        List<SpcyRsMhpzRole> isExistRole = spcyRsMhpzRoleService.list(new LambdaQueryWrapper<SpcyRsMhpzRole>()
                .eq(SpcyRsMhpzRole::getFmhid, rsMhpzRole.getFmhid())
                .eq(SpcyRsMhpzRole::getFroleid, rsMhpzRole.getFroleid()));
        if (CollectionUtils.isEmpty(isExistRole)) {
            rsMhpzRole.setId(GetUuIdUtils.ReplaceUuId());
            spcyRsMhpzRoleService.save(rsMhpzRole);
        }else {
            spcyRsMhpzRoleService.removeById(isExistRole.get(0).getId());
        }

        return HttpResult.ok("保存成功");
    }


    /**
     * 编辑
     *
     * @param spcyRsMhpz
     * @return
     */
    @Log(title = "审评查验-门户配置-编辑")
    @ApiOperation(value = "审评查验-门户配置-编辑")
    @PostMapping(value = "/editMhpz")
    public HttpResult<?> editMhpz(@RequestBody SpcyRsMhpz spcyRsMhpz) {
        if (StringUtils.isBlank(spcyRsMhpz.getId())){
            return HttpResult.error("主要参数为空");
        }
        spcyRsMhpzService.updateById(spcyRsMhpz);
        return HttpResult.ok("保存成功");
    }

    /**
     * 通过id删除
     *
     * @param ids
     * @return
     */
    @Log(title = "审评查验-门户配置-通过id删除")
    @ApiOperation(value = "审评查验-门户配置-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String ids) {
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数为空");
        }
        List<String> idsList = Arrays.asList(ids.split(",|，"));
        for (String id : idsList) {
            spcyRsMhpzService.removeById(id);
        }
        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-门户配置-通过id查询")
    @ApiOperation(value = "审评查验-门户配置-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsMhpz spcyRsMhpz = spcyRsMhpzService.getById(id);
        return HttpResult.ok(spcyRsMhpz);
    }

}
